package com.hopedove.tempdemo.repository

import android.graphics.Bitmap
import com.bumptech.glide.RequestManager
import com.hopedove.tempdemo.net.NoticeItem
import com.hopedove.tempdemo.net.data.TriangleArrangeItem
import com.hopedove.tempdemo.utils.*
import kotlinx.coroutines.CoroutineScope

object Repository {

    private var noticeList: MutableList<NoticeItem>? = null
    private var selectedItem: NoticeItem? = null

    fun saveNoticeList(list: List<NoticeItem>) {
        if (noticeList == null) {
            noticeList = mutableListOf()
        }

        noticeList?.clear()
        noticeList?.addAll(list)
    }

    fun getNoticeList(): List<NoticeItem> {
        return noticeList ?: mutableListOf()
    }


    fun saveSelectionItem(item: NoticeItem) {
        selectedItem = item
    }

    fun getSelectedItem(): NoticeItem? = selectedItem


    suspend fun buildTriangleArrange(
        scope: CoroutineScope,
        glide: RequestManager,
        rows: Int,
        cols: Int,
        list: List<TriangleArrangeItem>
    ): Bitmap? {


        val builder = GridBitmapBuilder(rows, cols, sideIndicate = setOf(SideIndicate.Bottom()))
        val bitmap = builder.build(false)

        // 收集所有的 url 对应的 bitmap
        val urls = list.map { it.VAL }.distinct()
        val map = collectMappingBitmaps(scope, glide, urls)

        val images = mutableListOf<GridCellBitmap>()
        for (item in list) {
            map[item.VAL]?.let { bmp ->
                images.add(GridCellBitmap(bmp, item.YCELL, item.XCELL))
            }
        }

        builder.drawCellBitmaps(images, GridCellCoordinate.LeftTop)
        return bitmap
    }
}